package ize.android;

import java.io.File;
import java.io.FileFilter;
import java.util.ArrayList;
import java.util.Collection;
import java.util.Collections;
import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

import android.R.anim;
import android.content.Context;
import android.content.res.TypedArray;
import android.preference.DialogPreference;
import android.util.AttributeSet;
import android.view.View;
import android.view.ViewGroup.LayoutParams;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;

public class FolderSelectDialog extends DialogPreference {
	private String defaultValue;	
	
	public FolderSelectDialog(Context context, AttributeSet attrs) {
		super(context, attrs);
		// TODO Auto-generated constructor stub
		setPersistent(true);
	}
	
	public void setValue(String value) {
        
        
        persistString(value);
        this.defaultValue = value;
        
      
    }
	
	@Override
	protected Object onGetDefaultValue(TypedArray a, int index) {
		final String value = a.getString(index);
 
		if (value == null) {
			return null;
		}
 
		this.defaultValue = value;
		
		
		return value;
	}
	
	@Override
    protected void onSetInitialValue(boolean restorePersistedValue, Object defaultValue) {
        setValue(restorePersistedValue ? getPersistedString((String) defaultValue) :
            (String) defaultValue);               
    }
	
	@Override
	protected View onCreateDialogView() {
		
		LinearLayout ll = new LinearLayout(getContext());
		ll.setOrientation(1);
		ll.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
                LayoutParams.FILL_PARENT));
		
		
		final ListView lv = new ListView(getContext());
		
		final TextView tv = new TextView(getContext());
		tv.setText("Selected folder : " + this.defaultValue);
		tv.setTextSize(15);
		
		ll.addView(tv);
		ll.addView(lv);
 
		final FileFilter filter = new FileFilter() {
			
			@Override
			public boolean accept(File pathname) {
				// TODO Auto-generated method stub
				return pathname.isDirectory();
			}
		};
		
		//list directories in current dir
		File[] files = new File(this.defaultValue).listFiles(filter);
		
		final List<String> dirlist = new ArrayList<String>();
		
		for (File file : files)
		{
			dirlist.add(file.getName());
			
		}
		
		Collections.sort(dirlist);
		dirlist.add(0, "..");
		
		
		lv.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dirlist));
		
		lv.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> a, View v, int pos, long id){
                // Now you have the id, you can set the background colour.
            	
            	//which dir is selected?
            	String selecteddir = dirlist.get(pos);
            	
            	if (selecteddir.equals(".."))
            	{
            		if ( defaultValue.lastIndexOf("/") > 1)
            			defaultValue = defaultValue.substring(0, defaultValue.lastIndexOf("/"));
            	}
            	else
            		defaultValue = defaultValue + "/" + selecteddir;
            	
            	tv.setText("Selected folder : " + defaultValue);
            	
            	File[] files = new File(defaultValue).listFiles(filter);
            	
            	//directory selected, clear the dir list and repopulate
            	dirlist.clear();
            	
            	for (File file : files)
        		{
        			dirlist.add(file.getName());
        			
        		}
        		
        		Collections.sort(dirlist);
        		dirlist.add(0, "..");
            	
            	
            	lv.setAdapter(new ArrayAdapter<String>(getContext(), android.R.layout.simple_list_item_1, dirlist));
            }
        });
 
		return ll;
	}
	
	@Override
	public void onDialogClosed(boolean positiveResult) {
		String result = defaultValue;
		if( positiveResult ) {
			if( isPersistent() )
			{
				persistString(result);
				System.out.println("persisting: " + result );
			}
			callChangeListener(result);
		}
	}
}
